//
//  ListViewController.m
//  iMiniTao
//
//  Created by liu nian on 13-8-17.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ListViewController.h"
#import "MeSource.h"
#import "ItemCell.h"
#import "RefreshCell.h"
#import "LolayGridView.h"
#import "ItemViewController.h"

#define kDefaultBottomBarHeight           38
#define kDefaultShadowLineHeight           0

@interface ListViewController ()<CuzyManagerDelegate,LolayGridViewDataSource,LolayGridViewDelegate,RefreshCellDelegate>{
    NSInteger   _index;
    BOOL        _reload;
    BOOL        _loadMore;
}
@property (nonatomic, assign) BOOL          isIphone5;
@property (nonatomic, retain) LolayGridView *gridView;
@property (nonatomic, retain) RefreshCell *headerCell;
@property (nonatomic, retain) RefreshCell   *footerCell;
@property (nonatomic, retain) NSMutableArray    *datasource;
@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UIImageView          *bottomImageView;
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) MeSource  *source;
@property (nonatomic, retain) UIActivityIndicatorView *indicatorView;
@property (strong, nonatomic) NSString *sortString;
@end

@implementation ListViewController

- (void)dealloc{
    _headerCell.delegate = nil;
    self.headerCell = nil;
    _footerCell.delegate = nil;
    self.footerCell = nil;
    _gridView.delegate = nil;
    self.gridView = nil;
}

- (id)initWithMeSource:(MeSource *)source
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.source = source;

        self.sortString = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view addSubview:self.navImageView];
    [self gridView];
    [self.view addSubview:self.bottomImageView];
    self.isIphone5 = self.view.frame.size.height > 480;
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tableViewDidScrollToTop{
    [self.gridView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.theTitle.text = self.source.name;
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.source.themeid, @"themeid",self.source.name, @"name", nil];
    [MobClick event:@"showProductList" attributes:dict];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.datasource.count == 0) {
        [self reloadItems];
    }
    
}
- (void)loadData{
    if (self.source.custom || self.source.itemtype == ITEMTYPEKEYWORD) {
        
        [[CuzyManager sharedManager] requstTBKItemsWithKeyWord:self.source.keyword
                                                    WithThemeID:@""
                                                WithPicSizeType:PicSize600
                                                       WithSort:self.sortString
                                                  WithPageIndex:_index withDelegate:self];
    }else{
        [[CuzyManager sharedManager] requstTBKItemsWithKeyWord:@""
                                                   WithThemeID:self.source.themeid
                                               WithPicSizeType:PicSize600
                                                      WithSort:self.sortString
                                                 WithPageIndex:_index withDelegate:self];
    }
}
- (void)reloadItems{
    if (_reload) {
        return;
    }
    [self.indicatorView startAnimating];
    _reload = YES;
    _index = 0;
    [self loadData];
}
- (void)reloadMoreItems{

    if (_loadMore) {
        return;
    }
    [self.indicatorView startAnimating];
    _loadMore = YES;
    _index++;
    [self loadData];
}
#pragma mark  DataManagerDelegate
-(void) updateViewForSuccess:(id)dataModel{
    [self.indicatorView stopAnimating];
    NSArray *items = dataModel;
    if (self.datasource.count == 0) {
        [self footerCell];
    }
    if (items && [items count]) {
        if (_reload) {
            _reload = NO;
            _index = 0;
            if ([items count] > 0) {
                [self.datasource removeAllObjects];
                [self.datasource addObjectsFromArray:items];
            }
        }
        
        if (_loadMore) {
            _loadMore = NO;
            [self.datasource addObjectsFromArray:items];
        }
        
        
        [self.gridView reloadData];
        [self.view sendSubviewToBack:self.gridView];
        [self.headerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        
    }else{
        [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        REMOVE_SAFELY(_footerCell);
    }
    [self loading:NO];
}
-(void) updateViewForError:(NSError *)errorInfo{
    [self.indicatorView stopAnimating];
    [self.headerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
    [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
    
    if (_reload) {
        _reload = NO;
    }
    
    if (_loadMore) {
        _loadMore = NO;
        _index--;
    }
}

#pragma mark LolayGridViewDataSource
- (NSInteger)numberOfRowsInGridView:(LolayGridView*)gridView
{
    NSInteger count = [self.datasource count];
    return ceil(1.0f*count/2);
}
- (NSInteger)numberOfColumnsInGridView:(LolayGridView*)gridView
{
    return 2;
}

- (LolayGridViewCell*)gridView:(LolayGridView*)gridView
                    cellForRow:(NSInteger)gridRowIndex
                      atColumn:(NSInteger)gridColumnIndex
{
    NSInteger objectIndex = gridRowIndex*2 + gridColumnIndex;
    if (objectIndex >= [self.datasource count]) {
        return nil;
    }
    
    static NSString *cellID = @"newsCell";
    ItemCell *cell = (ItemCell *)[gridView dequeueReusableGridCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[ItemCell alloc] initWithFrame:CGRectMake(0, 0, kItemCellWidth, kItemCellHeight) reuseIdentifier:cellID];
    }
    CuzyTBKItem *item = (CuzyTBKItem *)[self.datasource objectAtIndex:objectIndex];
    [cell updateWithItem:item];
    return cell;
}

#pragma mark LolayGridViewDelegate
- (CGFloat)heightForGridViewRows:(LolayGridView*)gridView
{
    return kItemCellHeight;
}
- (CGFloat)widthForGridViewColumns:(LolayGridView*)gridView
{
    return kItemCellWidth;
}
- (void)gridView:(LolayGridView*)gridView
didSelectCellAtRow:(NSInteger)gridRowIndex
        atColumn:(NSInteger)gridColumnIndex
{
    NSInteger objectIndex = gridRowIndex*2 + gridColumnIndex;
    
    ItemCell *cell = (ItemCell *)[gridView cellForRow:gridRowIndex atColumn:gridColumnIndex];
    
    CuzyTBKItem *item = (CuzyTBKItem *)[self.datasource objectAtIndex:objectIndex];
    ItemViewController *itemVC = [[ItemViewController alloc] initWithMeItem:item];
    itemVC.catalog = self.theTitle.text;
    itemVC.shareImage = cell.srcImageView.image;
    [self.navigationController pushViewController:itemVC animated:YES];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.headerCell refreshScrollViewDidScroll:scrollView];
    [_footerCell refreshScrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
     [self.headerCell refreshScrollViewDidEndDragging:scrollView];
    [_footerCell refreshScrollViewDidEndDragging:scrollView];
}

#pragma mark - RefreshCellDelegate
- (void)refreshCellDidTriggerLoading:(RefreshCell*)view{
    if (view == self.headerCell) {
        [self reloadItems];
    }else
        if (view == _footerCell) {
            [self reloadMoreItems];
        }
}

- (BOOL)refreshCellDataSourceIsLoading:(RefreshCell*)view{
     return self.headerCell.state == RefreshLoading || _footerCell.state==RefreshLoading;
}

- (NSDate*)refreshCellDataSourceLastUpdated:(RefreshCell*)view{
    return [NSDate date];
}

#pragma mark - getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        _navImageView.userInteractionEnabled = YES;
        _navImageView.backgroundColor = COLOR_RGB_NAV;
        [self.indicatorView setFrame:CGRectMake(CGRectGetWidth(_navImageView.frame) - 36 - 10, 5, 36, 36)];
        [_navImageView addSubview:self.indicatorView];
    }
    return _navImageView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}
- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 260, 40)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        _theTitle.textColor = [UIColor flatWhiteColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight-_kSpaceHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_BG_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        UIImage *imgTop = IMGNAMED(@"btn_top.png");
        UIButton *top = [UIButton buttonWithType:UIButtonTypeCustom];
        top.exclusiveTouch = YES;
        top.frame = CGRectMake(_bottomImageView.bounds.size.width-imgTop.size.width-10, floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [top addTarget:self action:@selector(tableViewDidScrollToTop) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:top];
        
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
        
        [top setBackgroundImage:IMGNAMED(@"btn_top.png") forState:UIControlStateNormal];
        [top setBackgroundImage:IMGNAMED(@"btn_top_light.png") forState:UIControlStateHighlighted];
        
    }
    return _bottomImageView;
}
- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:20];
    }
    return _datasource;
}
- (LolayGridView *)gridView{
    if (!_gridView) {
        _gridView = [[LolayGridView alloc] initWithFrame:CGRectMake(0,
                                                                 CGRectGetMaxY(self.navImageView.frame) - kDefaultShadowLineHeight,
                                                                 320,
                                                                 self.view.bounds.size.height - kDefaultBottomBarHeight-CGRectGetHeight(self.navImageView.frame)-_kSpaceHeight + kDefaultShadowLineHeight)];
        _gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _gridView.backgroundColor = COLOR_BG_VIEW;
        _gridView.topBounceEnabled = YES;
        _gridView.dataDelegate = self;
        _gridView.dataSource = self;
        _gridView.delegate = self;
        _gridView.showsVerticalScrollIndicator = NO;
        _gridView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_gridView];
    }
    return _gridView;
}

- (RefreshCell *)headerCell {
    if (!_headerCell) {
        _headerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                               delegate:self
                                         arrowImageName:@"refreshcell_img_arrow.png"
                                              textColor:[UIColor getColor:@"bebfc2"]
                                         indicatorStyle:UIActivityIndicatorViewStyleGray
                                                   type:RefreshTypeRefresh];
    }
    return _headerCell;
}
- (RefreshCell *)footerCell {
    if (!_footerCell) {
        _footerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                               delegate:self
                                         arrowImageName:@"refreshcell_img_arrow.png"
                                              textColor:[UIColor getColor:@"bebfc2"]
                                         indicatorStyle:UIActivityIndicatorViewStyleGray
                                                   type:RefreshTypeLoadMore];
    }
    return _footerCell;
}

@end
